import { message } from 'antd';
import { IUserListModel } from './interface';
import * as service from '@/service';
import { Callbacks } from 'jquery';

const userListModel: IUserListModel = {
  //todo1 命名空间
  namespace: 'userList',
  //todo2 定义state
  state: {
    userListData: {},
  },
  //todo3 定义effect 动作的创建者
  effects: {
    /*
        compParams 是组件发送过来的参数  {type,payload}
        call是用于发送异步数据请求的
        put是用于发送effects创建的action给reducers
      */
    //获取用户列表
    *getUserList(compParams, { call, put }) {
      const result = yield call(service.fetchUserList, compParams.params);
      // console.log('result', result);
      yield put({
        type: 'GET_USER_LIST',
        payload: result.data,
      });
    },
    // 添加用户
    *addUser(compParams, { call, put }) {
      const result = yield call(service.fetchAddUser, compParams.values);
      // console.log('result2', result);
      yield put({
        type: 'ADD_USER',
        payload: result.data,
      });
    },
    //删除用户
    *removeUser(compParams, { call, put }) {
      const result = yield call(service.fetchRemoveUser, compParams.params);
      // console.log('result', result);
      if (result.meta.status === 400) {
        message.error(result.meta.msg);
        return;
      }
      yield put({
        type: 'DELETE_USER',
        payload: compParams.params.id,
      });
    },
    //修改状态
    *modifyUser(compParams, { call, put }) {
      const result = yield call(service.fetchModifyUser, compParams.params);
      console.log('re1', result);
      yield put({
        type: 'MODIFY_USER',
        // payload:compParams.params.mg_state
      })
    },
  },
  //todo4 定义redurce
  reducers: {
    GET_USER_LIST(state, { payload }) {
      state.userListData = payload;
      // return {...state,userListData:payload}
    },
    ADD_USER(state, { payload }) {
      state.userListData.users.push(payload);
    },
    DELETE_USER(state, { payload }) {
      state.userListData.users = state.userListData.users.filter(
        (item: any) => {
          return item.id != payload;
        },
      );
    },
  },
};

export default userListModel;
